package com.pearlsoft.webapp.core.web.session;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pearlsoft.commons.utils.StringUtil;
import com.pearlsoft.webapp.core.web.util.HttpUtil;

/**
 * 
 * @Creator haitingr
 * @Create-Date 2010-12-28
 */
public class SessionTimeOutFilter implements Filter {

	protected static Log logger = LogFactory.getLog(SessionTimeOutFilter.class);

	private String sessionTimeOutTarget = "/index.jsp";

	private Set<String> exportUrl = new HashSet<String>();

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		String contextPath = httpRequest.getContextPath();

		String uri = httpRequest.getRequestURI();

		String innerUri = uri;

		if (!contextPath.equals("")) {
			innerUri = StringUtil.replace(uri, contextPath, "");
		}

		if (!innerUri.startsWith("/")) {
			innerUri = "/" + innerUri;
		}

		if (innerUri.equals("/")) {
			chain.doFilter(request, response);
			return;
		}

		SessionProfile user = HttpUtil.getUserProfileVO(httpRequest);

		if (!SessionTracker.validateRequest(httpRequest) || user == null) {
			if (exportUrl.contains(innerUri)) {
				chain.doFilter(request, response);
				return;
			} else {
				if (innerUri.indexOf("/ajax/") >= 0) {

				} else {
					((HttpServletResponse) response).sendRedirect(contextPath + sessionTimeOutTarget);
					return;
				}
			}
		}

		SessionTracker.trackCurrentSession((HttpServletRequest) request);
		chain.doFilter(request, response);
		return;

	}

	public void init(FilterConfig config) throws ServletException {
		this.sessionTimeOutTarget = config.getInitParameter("session-timeout-target");
		this.exportUrl = new HashSet<String>();
		this.exportUrl.add(this.sessionTimeOutTarget);

		String temp = config.getInitParameter("export-url");
		if (temp == null || temp.trim().equals("")) {
			return;
		}

		String[] ts = temp.split(",");
		for (int i = 0; i < ts.length; i++) {
			this.exportUrl.add(ts[i]);
		}
	}

}
